package mall.demo.filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import mall.demo.mybatis.service.AdminService;

/**
 * Servlet Filter implementation class AdminAuthFilter
 */
@WebFilter(
		urlPatterns = { 
				"/admin/*",
				"/servlet/AddProductServlet",
				"/servlet/delproduct",
				"/servlet/updateproduct"
		}, 
		//below not work
		servletNames = { 
				"AddProductServlet", 
				"DeleteProductServlet", 
				"UpdateProductServlet"
		})
public class AdminAuthFilter implements Filter {
	private static Logger logger = LoggerFactory.getLogger(AdminAuthFilter.class);
    /**
     * Default constructor. 
     */
    public AdminAuthFilter() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		// TODO Auto-generated method stub
		// place your code here
		HttpServletRequest httpReq = (HttpServletRequest) request;
		HttpServletResponse httpResp = (HttpServletResponse) response;
		logger.info(httpReq.getRequestURI());
		String url = httpReq.getRequestURI();
		if (!url.startsWith(httpReq.getContextPath() + "/admin/login.jsp")) {
			boolean isAdmin = (new AdminService()).isAdminLogged(httpReq.getSession());
			if(!isAdmin) {
				//no admin login. 
				httpResp.sendRedirect(httpReq.getContextPath() + "/admin/login.jsp");
				return;
			}
		}
		// pass the request along the filter chain
		chain.doFilter(request, response);
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

}
